package com.uzai.console.service.configplan.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.dy.dytoken.DyTokenQuery;
import com.uzai.console.dto.jd.jdtoken.JdTokenQuery;
import com.uzai.console.dto.locallive.tlbtoken.TlbTokenQuery;
import com.uzai.console.dto.pdd.pddtoken.PddTokenQuery;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleQuery;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleQuery;
import com.uzai.console.dto.sysdomain.SysDomainQuery;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.vph.vphtoken.VphTokenQuery;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanAccountBatchUpdateDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanAccountUpdateDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanAddDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanCopyDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanIdDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanNormalrewardruleDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanPluginBatchUpdateDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanPluginIdDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanPluginUpdateDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanProfitUpdateDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanQuery;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanUpdateDto;
import com.uzai.console.entity.ConfigPlan;
import com.uzai.console.entity.DyToken;
import com.uzai.console.entity.JdToken;
import com.uzai.console.entity.NormalRewardRule;
import com.uzai.console.entity.PddToken;
import com.uzai.console.entity.RegRewardRule;
import com.uzai.console.entity.RobotCmd;
import com.uzai.console.entity.SysDomain;
import com.uzai.console.entity.SysPlugin;
import com.uzai.console.entity.TbToken;
import com.uzai.console.entity.TlbToken;
import com.uzai.console.entity.UserType;
import com.uzai.console.entity.VphToken;
import com.uzai.console.mapper.DyTokenMapper;
import com.uzai.console.mapper.JdTokenMapper;
import com.uzai.console.mapper.NormalRewardRuleMapper;
import com.uzai.console.mapper.PddTokenMapper;
import com.uzai.console.mapper.RegRewardRuleMapper;
import com.uzai.console.mapper.RobotCmdMapper;
import com.uzai.console.mapper.SysDomainMapper;
import com.uzai.console.mapper.SysPluginMapper;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.mapper.TlbTokenMapper;
import com.uzai.console.mapper.UserTypeMapper;
import com.uzai.console.mapper.VphTokenMapper;
import com.uzai.console.mapper.WechatUserMapper;
import com.uzai.console.mapper.WxpubConfigPlanMapper;
import com.uzai.console.service.configplan.WxpubConfigPlanService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.rebotcmd.RobotCmdService;
import com.uzai.console.vo.base.SelectIdVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.sysdomain.SysDomainInfoVo;
import com.uzai.console.vo.sysplugin.SysPluginVo;
import com.uzai.console.vo.wechatprivate.configplan.ConfigPlanSelectListVo;
import com.uzai.console.vo.wechatprivate.configplan.ConfigPlanVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author cen
 * @date 2022-4-26 09:51:55
 */
@Service
@Slf4j
public class WxpubConfigPlanServiceImpl implements WxpubConfigPlanService {

    @Autowired
    private WxpubConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private DyTokenMapper dyTokenMapper;
    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private RegRewardRuleMapper regRewardRuleMapper;
    @Autowired
    private SysDomainMapper sysDomainMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RobotCmdService robotCmdService;
    @Autowired
    private RobotCmdMapper robotCmdMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private TlbTokenMapper tlbTokenMapper;


    /**
     * 查询配置方案下拉列表
     * @param query
     * @return null
     */
    public List<ConfigPlanSelectListVo> findConfigPlanSelectList(ConfigPlanQuery query){
        //新建返回配置方案下拉列表
        ArrayList<ConfigPlanSelectListVo>  selectList = new ArrayList<ConfigPlanSelectListVo>();
        //查询数据库中的配置方案
        ArrayList<ConfigPlan> configPlanList = configPlanMapper.findByList(query);
        if(configPlanList != null && configPlanList.size() > 0){
            for (ConfigPlan configPlan : configPlanList){
                ConfigPlanSelectListVo selectListVo = new ConfigPlanSelectListVo();
                BeanUtils.copyProperties(configPlan, selectListVo);
                selectList.add(selectListVo);
            }
        }
        return selectList;
    }

    /**
     * 查询配置方案详情
     * @param configPlanIdDto
     * @return null
     */
    public ConfigPlanVo findConfigPlanInfo(ConfigPlanIdDto configPlanIdDto){
        if(configPlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //查询配置方案信息
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanIdDto.getId(), configPlanIdDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }
        //返回页面列表
        ConfigPlanVo configPlanVo = new ConfigPlanVo();
        //对象复制
        BeanUtils.copyProperties(configPlan, configPlanVo);

        return configPlanVo;
    }

    /**
     * 查询默认配置方案详情
     * @param merId
     * @param deviceType
     * @return null
     */
    public ConfigPlanVo findConfigPlanInfoIsDefault(Long merId, String deviceType){
        if(merId == null || StringUtils.isBlank(deviceType)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //返回页面列表
        ConfigPlanVo configPlanVo = new ConfigPlanVo();

        //查询配置方案信息
        ConfigPlan configPlan = configPlanMapper.selectByIsDefault(merId, deviceType);
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置默认配置方案");
        }

        //对象复制
        BeanUtils.copyProperties(configPlan, configPlanVo);

        return configPlanVo;
    }

    /**
     * 添加配置方案详情
     * @param configPlanAddDto
     * @return null
     */
    public Long addConfigPlan(ConfigPlanAddDto configPlanAddDto){

        if(configPlanAddDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先登录系统");
        }

        if(StringUtils.isBlank(Tools.getStr(configPlanAddDto.getName())) || StringUtils.isBlank(Tools.getStr(configPlanAddDto.getDeviceType()))){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //验证名称重复
        ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanAddDto.getName(), configPlanAddDto.getMerId(), configPlanAddDto.getDeviceType());
        if(configPlan_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }

        Integer now = DateUtil.getNowTime();
        ConfigPlan configPlan = new ConfigPlan();
        Long id = IdWorker.getId();
        configPlan.setId(id);
        configPlan.setDeviceType(configPlanAddDto.getDeviceType());
        configPlan.setMerId(configPlanAddDto.getMerId());
        configPlan.setName(configPlanAddDto.getName());
        configPlan.setCreateTime(now);
        configPlan.setUpdateTime(now);

        //查询数据库是否有默认
        ConfigPlan configPlanIsDefault = configPlanMapper.selectByIsDefault(configPlanAddDto.getMerId(), configPlanAddDto.getDeviceType());
        if(configPlanIsDefault == null){
            configPlan.setIsDefault(1);
        }else{
            configPlan.setIsDefault(0);
        }

        //保存数据库
        configPlanMapper.insert(configPlan);
        //返回到前台
        return id;
    }

    /**
     * 修改配置方案详情
     * @param configPlanUpdateDto
     * @return null
     */
    public void updateConfigPlan(ConfigPlanUpdateDto configPlanUpdateDto){

        if(configPlanUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(configPlanUpdateDto.getName() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan_old = configPlanMapper.selectById(configPlanUpdateDto.getId(), configPlanUpdateDto.getMerId());
        if(configPlan_old == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //验证新名字是否已经存在
        if(!configPlan_old.getName().equals(configPlanUpdateDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanUpdateDto.getName(), configPlan_old.getMerId(), configPlan_old.getDeviceType());
            if(configPlan_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
            }
        }

        //配置方案名称
        configPlan_old.setName(configPlanUpdateDto.getName());
        //修改时间
        configPlan_old.setUpdateTime(DateUtil.getNowTime());
        //保存数据库
        configPlanMapper.updateByIdSelective(configPlan_old);
    }

    /**
     * 设置默认配置方案
     * @param configPlanUpdateDto
     * @return null
     */
    @Transactional
    public void setDefault(ConfigPlanUpdateDto configPlanUpdateDto){

        if(configPlanUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanUpdateDto.getId(), configPlanUpdateDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        Integer now = DateUtil.getNowTime();

        //将已经存在的默认配置改成非默认
        ConfigPlan configPlan_default = configPlanMapper.selectByIsDefault(configPlan.getMerId(), configPlan.getDeviceType());

        if(configPlan_default != null) {
            configPlan_default.setIsDefault(0);
            configPlan_default.setUpdateTime(now);
            configPlanMapper.update(configPlan_default);
        }

        //设置新的默认
        configPlan.setIsDefault(1);
        configPlan.setUpdateTime(now);
        configPlanMapper.updateByIdSelective(configPlan);
    }

    /**
     * 删除配置方案详情
     * @param configPlanIdDto
     * @return null
     */
    @Transactional
    public void deleteConfigPlan(ConfigPlanIdDto configPlanIdDto){

        if(configPlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //将配置方案查询出来
        ConfigPlan configPlan =  configPlanMapper.selectById(configPlanIdDto.getId(), configPlanIdDto.getMerId());
        if(configPlan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //先判断是否有机器人在使用该配置，如果有则无法删除
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setMerId(configPlanIdDto.getMerId());
        deviceQuery.setDeviceType(configPlan.getDeviceType());
        deviceQuery.setConfigId(configPlan.getId());
        List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
        if(deviceList != null && deviceList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案已经有机器人在使用，不能删除");
        }

        //批量删除用
        List<Long> idList = new ArrayList<Long>();

        //删除淘宝插件ID
        if(configPlan.getTbId() != null ){
            //sysPluginMapper.deleteById(configPlan.getTbId());
            idList.add(configPlan.getTbId());
        }
        //删除京东插件id
        if(configPlan.getJdId() != null ){
            //sysPluginMapper.deleteById(configPlan.getJdId());
            idList.add(configPlan.getJdId());
        }
        //删除拼多多插件id
        if(configPlan.getPddId() != null ){
            //sysPluginMapper.deleteById(configPlan.getPddId());
            idList.add(configPlan.getPddId());
        }
        //删除唯品会插件id
        if(configPlan.getVphId() != null ){
            //sysPluginMapper.deleteById(configPlan.getVphId());
            idList.add(configPlan.getVphId());
        }
        //删除抖音插件id
        if(configPlan.getDyId() != null ){
            //sysPluginMapper.deleteById(configPlan.getVphId());
            idList.add(configPlan.getDyId());
        }
        //删除本地生活插件id
        if(configPlan.getLocalLiveId() != null ){
            //sysPluginMapper.deleteById(configPlan.getLocalLiveId());
            idList.add(configPlan.getLocalLiveId());
        }
        //删除微信好友添加插件id
        if(configPlan.getWxUserAddId() != null ){
            //sysPluginMapper.deleteById(configPlan.getWxUserAddId());
            idList.add(configPlan.getWxUserAddId());
        }
        //删除好友引导插件id
        if(configPlan.getUserGuideId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserGuideId());
            idList.add(configPlan.getUserGuideId());
        }
        //删除推广裂变插件id
        if(configPlan.getUserExpandFissionId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserExpandFissionId());
            idList.add(configPlan.getUserExpandFissionId());
        }
        //删除自动备注插件id
        if(configPlan.getUserAutoRemarkId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserAutoRemarkId());
            idList.add(configPlan.getUserAutoRemarkId());
        }
        //删除提现插件id
        if(configPlan.getUserTakeBalId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserTakeBalId());
            idList.add(configPlan.getUserTakeBalId());
        }
        //删除个人信息查询插件id
        if(configPlan.getUserInfoQueryId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserInfoQueryId());
            idList.add(configPlan.getUserInfoQueryId());
        }
        //删除用户签到插件id
        if(configPlan.getUserSigninId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserSigninId());
            idList.add(configPlan.getUserSigninId());
        }
        //删除社群管理插件id
        if(configPlan.getCommunityId() != null ){
            //sysPluginMapper.deleteById(configPlan.getCommunityId());
            idList.add(configPlan.getCommunityId());
        }
        //删除订阅消息插件id
        if(configPlan.getSubscribeMsgId() != null ){
            //sysPluginMapper.deleteById(configPlan.getSubscribeMsgId());
            idList.add(configPlan.getSubscribeMsgId());
        }
        //删除其他设置插件id
        if(configPlan.getOtherId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getOtherId());
        }
        //删除导购插件id
        if(configPlan.getShoppingGuideId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getShoppingGuideId());
        }
        //删除微信公众号设置插件id
        if(configPlan.getWxpubSettingId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getWxpubSettingId());
        }

        //删除配置方案数据
        configPlanMapper.deleteById(configPlanIdDto.getId(), configPlanIdDto.getMerId());

        //批量删除插件设置
        if(idList != null && idList.size() > 0){
            sysPluginMapper.batchDelete(idList);
            //删除redis缓存
            for (Long id : idList){
                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.delete(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), id));
            }
        }

        //删除指令表
        robotCmdMapper.deleteByConfigId(configPlanIdDto.getMerId(), configPlanIdDto.getId());

        //删除redis缓存中的指令
        redisTemplate.delete(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanIdDto.getId()));

    }

    /**
     * 复制配置方案
     * @param configPlanCopyDto
     * @return null
     */
    @Transactional
    public Long copyConfigPlan(ConfigPlanCopyDto configPlanCopyDto){
        //判断ID是否未空
        if(configPlanCopyDto.getId() == null || StringUtils.isBlank(configPlanCopyDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //通过ID查询配置方案
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanCopyDto.getId(), configPlanCopyDto.getMerId());
        if(configPlan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前的配置方案不存在");
        }

        //验证名称重复
        ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanCopyDto.getName(), configPlan.getMerId(), configPlan.getDeviceType());
        if(configPlan_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }

        Integer now = DateUtil.getNowTime();

        //复制插件件信息
        List<SysPlugin> sysPluginsList = new ArrayList<SysPlugin>();

        //淘宝插件ID
        if(configPlan.getTbId() != null ){
            //查询淘宝插件
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getTbId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加淘宝插件
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的淘宝插件
                configPlan.setTbId(id);
            }
        }

        //京东插件id
        if(configPlan.getJdId()!= null ){
            //查询京东插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getJdId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加京东插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的京东插件id
                configPlan.setJdId(id);
            }
        }

        //拼多多插件id
        if(configPlan.getPddId()!= null ){
            //查询拼多多插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getPddId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加拼多多插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的拼多多插件id
                configPlan.setPddId(id);
            }
        }

        //唯品会插件id
        if(configPlan.getVphId()!= null ){
            //查询唯品会插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getVphId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加唯品会插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的唯品会插件id
                configPlan.setVphId(id);
            }
        }

        //抖音插件id
        if(configPlan.getDyId()!= null ){
            //查询唯品会插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getDyId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加唯品会插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的唯品会插件id
                configPlan.setDyId(id);
            }
        }

        //本地生活插件id
        if(configPlan.getLocalLiveId()!= null ){
            //查询本地生活插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getLocalLiveId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加本地生活插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的本地生活插件id
                configPlan.setLocalLiveId(id);

                //本地生活指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.LOCAL_LIVE.getValue(), sysPlugin.getData());

            }
        }

        //微信好友添加插件id
        if(configPlan.getWxUserAddId()!= null ){
            //查询微信好友添加插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWxUserAddId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加微信好友添加插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的微信好友添加插件id
                configPlan.setWxUserAddId(id);
            }
        }

        //推广裂变插件id
        if(configPlan.getUserExpandFissionId()!= null ){
            //查询推广裂变插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserExpandFissionId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加推广裂变插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的推广裂变插件id
                configPlan.setUserExpandFissionId(id);
            }
        }

        //提现插件id
        if(configPlan.getUserTakeBalId()!= null ){
            //查询提现插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加提现插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中提现插件id
                configPlan.setUserTakeBalId(id);

                //保存提现指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_TAKE_BAL.getValue(), sysPlugin.getData());

            }
        }

        //好友引导插件id
        if(configPlan.getUserGuideId()!= null ){
            //好友引导插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserGuideId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加好友引导插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中好友引导插件id
                configPlan.setUserGuideId(id);
            }
        }

        //自动备注插件id
        if(configPlan.getUserAutoRemarkId()!= null ){
            //自动备注插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserAutoRemarkId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加自动备注插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中自动备注插件id
                configPlan.setUserAutoRemarkId(id);
            }
        }

        //订阅消息插件id
        if(configPlan.getSubscribeMsgId()!= null ){
            //订阅消息插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getSubscribeMsgId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加订阅消息插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中订阅消息插件id
                configPlan.setSubscribeMsgId(id);

                //保存订阅指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.SUBSCRIBE_MSG.getValue(), sysPlugin.getData());
            }
        }

        //个人信息查询插件id
        if(configPlan.getUserInfoQueryId()!= null ){
            //订阅消息插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserInfoQueryId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加个人信息查询插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中个人信息查询插件id
                configPlan.setUserInfoQueryId(id);

                //保存个人信息指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_INFO_QUERY.getValue(), sysPlugin.getData());

            }
        }

        //用户签到插件id
        if(configPlan.getUserSigninId()!= null ){
            //用户签到插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserSigninId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加用户签到插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中用户签到插件id
                configPlan.setUserSigninId(id);

                //保存用户签到指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_SIGNIN.getValue(), sysPlugin.getData());

            }
        }

        //社群管理插件id
        if(configPlan.getCommunityId()!= null ){
            //社群管理插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getCommunityId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加社群管理插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中社群管理插件id
                configPlan.setCommunityId(id);

                //保存社群指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.COMMUNITY.getValue(), sysPlugin.getData());

            }
        }

        //其他设置插件id
        if(configPlan.getOtherId()!= null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setOtherId(id);
            }
        }

        //导购插件
        if(configPlan.getShoppingGuideId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getShoppingGuideId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setShoppingGuideId(id);
            }
        }

        //微信公众号设置插件
        if(configPlan.getWxpubSettingId() != null ){
            //微信公众号设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWxpubSettingId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setShoppingGuideId(id);
            }
        }

        //批量插入插件
        if(sysPluginsList != null & sysPluginsList.size() > 0){
            sysPluginMapper.batchAdd(sysPluginsList);
            for(SysPlugin sysPlugin : sysPluginsList){
                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5, TimeUnit.DAYS);
            }
        }

        //添加新的配置方案
        //生成新的配置ID
        Long configPlanId_new = IdWorker.getId();
        configPlan.setId(configPlanId_new);
        configPlan.setName(configPlanCopyDto.getName());
        configPlan.setCreateTime(now);
        configPlan.setUpdateTime(now);
        configPlan.setIsDefault(0); //不默认
        configPlanMapper.insert(configPlan);

        //查出旧指令列表
        List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanCopyDto.getMerId(), configPlanCopyDto.getId());
        if(robotCmdList != null && robotCmdList.size() > 0){
            for (RobotCmd robotCmd : robotCmdList){
                robotCmd.setId(IdWorker.getId()); //更新旧指令ID
                robotCmd.setConfigId(configPlanId_new);//更新旧指令配置方案
                robotCmd.setUpdateTime(now);
                robotCmd.setCreateTime(now);
            }

            //批量插入指令表数据库
            robotCmdMapper.batchAdd(robotCmdList);

            //更新新的指令缓存redis
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanId_new), data);

        }

        return configPlanId_new;

    }

    /**
     * 查询插件
     * @param configPlanPluginIdDto
     * @return null
     */
    public SysPluginVo findSysPluginInfo(ConfigPlanPluginIdDto configPlanPluginIdDto){

        if(configPlanPluginIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlanPluginIdDto.getId(), configPlanPluginIdDto.getMerId());
        if(sysPlugin == null){
            sysPlugin = new SysPlugin();
        }
        //返回给页面的对象
        SysPluginVo sysPluginVo = new SysPluginVo();
        BeanUtils.copyProperties(sysPlugin, sysPluginVo);
        return  sysPluginVo;

    }

    /**
     * 修改插件信息
     * @param configPlanPluginUpdateDto
     * @return null
     */
    @Transactional
    public void updateSysPlugin(ConfigPlanPluginUpdateDto configPlanPluginUpdateDto){
        if(configPlanPluginUpdateDto.getConfigPlanID() == null || StringUtils.isBlank(configPlanPluginUpdateDto.getPlugName()) || StringUtils.isBlank(configPlanPluginUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //页面传过来的是驼峰型，末尾是Id的后缀去掉末尾Id
        String plugName_hump = configPlanPluginUpdateDto.getPlugName().replaceAll("Id","");
        //驼峰型转成下划线型
        String plugName = Tools.humpToLine(plugName_hump);

        //查询配置方案
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanPluginUpdateDto.getConfigPlanID(), configPlanPluginUpdateDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }


        //插件ID存在，则修改
        if(configPlanPluginUpdateDto.getId() != null){
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlanPluginUpdateDto.getId(), configPlan.getMerId());
            if(sysPlugin != null){
                //重新添加
                Integer now = DateUtil.getNowTime();
                sysPlugin.setData(configPlanPluginUpdateDto.getData());
                sysPlugin.setUpdateTime(now);
                sysPluginMapper.update(sysPlugin);

                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);
            }else{//该ID插件不存在，先清除redis缓存，在重新添加插件
                //清除缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), configPlanPluginUpdateDto.getId()));

                //重新添加
                Integer now = DateUtil.getNowTime();
                Long id = IdWorker.getId();
                sysPlugin = new SysPlugin();
                sysPlugin.setId(id);
                sysPlugin.setMerId(configPlanPluginUpdateDto.getMerId());
                sysPlugin.setPlugName(plugName);
                sysPlugin.setData(configPlanPluginUpdateDto.getData());
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                sysPluginMapper.insert(sysPlugin);

                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                //反射配置方案类，设置对应的插件ID
                Class cls = configPlan.getClass();
                Field field = null;
                try {
                    field = cls.getDeclaredField(configPlanPluginUpdateDto.getPlugName());
                    field.setAccessible(true);//设置允许访问
                    field.set(configPlan, id);
                    //修改配置方案
                    configPlanMapper.update(configPlan);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }else{//插件ID不存在，则新增
            Integer now = DateUtil.getNowTime();
            Long id = IdWorker.getId();
            SysPlugin sysPlugin = new SysPlugin();
            sysPlugin.setId(id);
            sysPlugin.setMerId(configPlanPluginUpdateDto.getMerId());

            sysPlugin.setPlugName(plugName);
            sysPlugin.setData(configPlanPluginUpdateDto.getData());
            sysPlugin.setCreateTime(now);
            sysPlugin.setUpdateTime(now);
            sysPluginMapper.insert(sysPlugin);

            //修改插件更新缓存，确保缓存和数据库一致
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

            //反射配置方案类，设置对应的插件ID
            Class cls = configPlan.getClass();
            Field field = null;
            try {
                field = cls.getDeclaredField(configPlanPluginUpdateDto.getPlugName());
                field.setAccessible(true);//设置允许访问
                field.set(configPlan, id);
                //修改配置方案
                configPlanMapper.update(configPlan);
            } catch (Exception e) {
            }
        }

        //如果是其他插件,需要将信息添加到Redis当中得 设备消息回复配置信息
        if("other".equals(plugName_hump)){
            //查询该所有使用过该配置得机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(configPlan.getMerId());
            deviceQuery.setDeviceType(configPlan.getDeviceType());
            deviceQuery.setConfigId(configPlan.getId());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
               for (DeviceInfoVo deviceInfoVo : deviceList){
                   redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceInfoVo.getId()) , configPlanPluginUpdateDto.getData());
               }
            }
        }

        if(configPlanPluginUpdateDto.getConfigPlanID() != null){
            //修改指令
            robotCmdService.addRobotCmdForConfigPlan(configPlanPluginUpdateDto.getMerId(), configPlanPluginUpdateDto.getConfigPlanID(), plugName, configPlanPluginUpdateDto.getData());
            //更新指令redis缓存
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanPluginUpdateDto.getMerId(), configPlanPluginUpdateDto.getConfigPlanID());
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanPluginUpdateDto.getConfigPlanID()), data);
        }
    }

    /**
     * 批量修改插件
     * @param configPlanPluginBatchUpdateDto
     * @return null
     */
    @Transactional
    public void batchUpdateSysPlugin(ConfigPlanPluginBatchUpdateDto configPlanPluginBatchUpdateDto){

        List<Long> configPlanIdList = configPlanPluginBatchUpdateDto.getConfigPlanIDList();

        if(configPlanIdList == null || StringUtils.isBlank(configPlanPluginBatchUpdateDto.getPlugName()) || StringUtils.isBlank(configPlanPluginBatchUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        JSONObject dataJSONObject_para = JSONObject.parseObject(configPlanPluginBatchUpdateDto.getData());
        if(dataJSONObject_para == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Set<String> keySet_para =  dataJSONObject_para.keySet();
        if(keySet_para == null || keySet_para.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //页面传过来的是驼峰型，末尾是Id的后缀去掉末尾Id
        String plugName_hump = configPlanPluginBatchUpdateDto.getPlugName().replaceAll("Id","");
        //驼峰型转成下划线型
        String plugName = Tools.humpToLine(plugName_hump);

        //更新事件
        Integer now = DateUtil.getNowTime();

        for (Long configPlanId : configPlanIdList){
            //查询配置方案
            ConfigPlan configPlan = configPlanMapper.selectById(configPlanId, configPlanPluginBatchUpdateDto.getMerId());
            if(configPlan == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
            }

            //通过反射机制，获取对应的插件id
            Long  pluginId = (Long)Tools.getValueByReflex(configPlan, configPlanPluginBatchUpdateDto.getPlugName());
            //临时保存最新的插件数据，修改指令时使用。
            String data_other = "";

            if(pluginId != null){ //插件存在，
                SysPlugin sysPlugin = sysPluginMapper.selectById(pluginId, configPlan.getMerId());
                if(sysPlugin != null){ //插件表中查询到该插件
                    //则修改该插件内容
                    JSONObject jsonObject_value = JSONObject.parseObject(sysPlugin.getData());
                    if(jsonObject_value ==  null){
                        jsonObject_value = new JSONObject();
                    }
                    //替换
                    for (String key_para : keySet_para) {
                        Object value_vara = dataJSONObject_para.get(key_para);
                        jsonObject_value.put(key_para, value_vara);
                    }
                    sysPlugin.setData(jsonObject_value.toJSONString());
                    sysPlugin.setUpdateTime(now);
                    sysPluginMapper.update(sysPlugin);

                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                    //其他插件内容
                    data_other = sysPlugin.getData();

                }else{//该ID插件不存在，先清除redis缓存，在重新添加插件
                    //重新添加
                    Long id = IdWorker.getId();
                    sysPlugin = new SysPlugin();
                    sysPlugin.setId(pluginId);
                    sysPlugin.setMerId(configPlanPluginBatchUpdateDto.getMerId());
                    sysPlugin.setPlugName(plugName);
                    sysPlugin.setData(dataJSONObject_para.toJSONString());
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    sysPluginMapper.insert(sysPlugin);

                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                    //其他插件内容
                    data_other = sysPlugin.getData();
                }
            }else{ //插件不存在, 新增插件，还得反射修改配置方案中对应的插件id
                Long id = IdWorker.getId();
                SysPlugin sysPlugin = new SysPlugin();
                sysPlugin.setId(id);
                sysPlugin.setMerId(configPlanPluginBatchUpdateDto.getMerId());
                sysPlugin.setPlugName(plugName);
                sysPlugin.setData(dataJSONObject_para.toJSONString());
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                sysPluginMapper.insert(sysPlugin);

                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                //其他插件内容
                data_other = sysPlugin.getData();

                //反射配置方案类，设置对应的插件ID
                Tools.setValueByReflex(configPlan, configPlanPluginBatchUpdateDto.getPlugName(), id);
                //修改配置方案
                configPlanMapper.update(configPlan);

            }

            //如果是其他插件,需要将信息添加到Redis当中得 设备消息回复配置信息
            if("other".equals(plugName_hump)){
                //查询该所有使用过该配置得机器人
                DeviceQuery deviceQuery = new DeviceQuery();
                deviceQuery.setMerId(configPlan.getMerId());
                deviceQuery.setDeviceType(configPlan.getDeviceType());
                deviceQuery.setConfigId(configPlan.getId());
                List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
                if(deviceList != null && deviceList.size() > 0){
                    for (DeviceInfoVo deviceInfoVo : deviceList){
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceInfoVo.getId()) , data_other);
                    }
                }
            }

            //修改指令
            robotCmdService.addRobotCmdForConfigPlan(configPlanPluginBatchUpdateDto.getMerId(), configPlanId, plugName, data_other);
            //更新指令redis缓存
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanPluginBatchUpdateDto.getMerId(), configPlanId);
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanId), data);
        }
    }


    /**
     * 修改配置方案中的联盟
     * @param configPlanAccountUpdateDto
     * @return null
     */
    public void updateConfigPlanAccount(ConfigPlanAccountUpdateDto configPlanAccountUpdateDto){

        if(configPlanAccountUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan = configPlanMapper.selectById(configPlanAccountUpdateDto.getId(), configPlanAccountUpdateDto.getMerId());

        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //淘宝联盟ID
        configPlan.setTbAccountId(configPlanAccountUpdateDto.getTbAccountId());
        //淘宝炮灰订单类型
        configPlan.setPhTbOrderType(configPlanAccountUpdateDto.getPhTbOrderType());

        //唯品会联盟ID
        configPlan.setVphAccountId(configPlanAccountUpdateDto.getVphAccountId());
        //唯品会炮灰订单类型
        configPlan.setPhVphOrderType(configPlanAccountUpdateDto.getPhVphOrderType());

        //京东联盟ID
        configPlan.setJdAccountId(configPlanAccountUpdateDto.getJdAccountId());

        //拼多多账号类型（0自有账号，1推老板共享账号）
        configPlan.setPddAccountType(configPlanAccountUpdateDto.getPddAccountType());
        //拼多多联盟账号
        configPlan.setPddAccountId(configPlanAccountUpdateDto.getPddAccountId());
        //拼多多共享推老板账号
        configPlan.setTlbPddAccountId(configPlanAccountUpdateDto.getTlbPddAccountId());

        //美团账号类型（0自有账号，1推老板共享账号）
        configPlan.setMtAccountType(configPlanAccountUpdateDto.getMtAccountType());
        //美团共享推老板联盟
        configPlan.setTlbMtAccountId(configPlanAccountUpdateDto.getTlbMtAccountId());

        //饿了么联盟id
        configPlan.setElmAccountId(configPlanAccountUpdateDto.getElmAccountId());

        //抖音联盟
        configPlan.setDyAccountId(configPlanAccountUpdateDto.getDyAccountId());
        //抖音共享推老板联盟
        configPlan.setTlbDyAccountId(configPlanAccountUpdateDto.getTlbDyAccountId());
        //抖音账号类型（0自有账号，1推老板共享账号）
        configPlan.setDyAccountType(configPlanAccountUpdateDto.getDyAccountType());
        configPlan.setPhDyOrderType(configPlanAccountUpdateDto.getPhDyOrderType());

        //修改配置方案
        configPlanMapper.update(configPlan);

    }

    /**
     * 批量修改配置方案中的联盟
     * @param configPlanAccountBatchUpdateDto
     * @return null
     */
    @Transactional
    public void batchUpdateConfigPlanAccount(ConfigPlanAccountBatchUpdateDto configPlanAccountBatchUpdateDto){
        List<Long> configPlanIdList = configPlanAccountBatchUpdateDto.getConfigPlanIDList();
        if(configPlanIdList == null || configPlanIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(StringUtils.isBlank(configPlanAccountBatchUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        JSONObject dataJSONObject = JSONObject.parseObject(configPlanAccountBatchUpdateDto.getData());
        if(dataJSONObject == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Set<String> keySet =  dataJSONObject.keySet();
        if(keySet == null || keySet.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long configPlanId : configPlanIdList){
            ConfigPlan configPlan = configPlanMapper.selectById(configPlanId, configPlanAccountBatchUpdateDto.getMerId());
            if(configPlan != null){
                for (String key : keySet){
                    Object value = dataJSONObject.get(key);
                    //反射配置方案类，设置对应的插件ID
                    Class cls = configPlan.getClass();
                    Field field = null;
                    try {
                        field = cls.getDeclaredField(key);
                        field.setAccessible(true);//设置允许访问
                        field.set(configPlan, value);
                        //修改配置方案
                        configPlanMapper.update(configPlan);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }


    /**
     * 修改配置方案中的分佣
     * @param configPlanProfitUpdateDto
     * @return null
     */
    public void updateConfigPlanProfit(ConfigPlanProfitUpdateDto configPlanProfitUpdateDto){

        if(configPlanProfitUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan = configPlanMapper.selectById(configPlanProfitUpdateDto.getId(), configPlanProfitUpdateDto.getMerId());

        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //用户会员组
        if(configPlanProfitUpdateDto.getUserTypeGroupId() != null){
            if(Tools.getLong(configPlan.getUserTypeGroupId()).longValue() != 0){ //已经配置了会员类型组
                //验证是否修改了会员类型组，如果修改了，则需要判断该会员类型组内的任一会员类型是否有用户使用，如果有，则不允许修改
                if(Tools.getLong(configPlan.getUserTypeGroupId()).longValue() != configPlanProfitUpdateDto.getUserTypeGroupId().longValue()){
                    //查询该会员类型组内所有的会员类型
                    UserTypeQuery userTypeQuery = new UserTypeQuery();
                    userTypeQuery.setMerId(configPlanProfitUpdateDto.getMerId());
                    userTypeQuery.setGroupId(configPlan.getUserTypeGroupId());
                    List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
                    if(userTypeList != null && userTypeList.size() > 0){
                        //查询该类型组内所有的会员类型是否有用户在使用，如果在使用，则不允许修改
                        WechatUserQuery wechatUserQuery = new WechatUserQuery();
                        wechatUserQuery.setMerId(configPlanProfitUpdateDto.getMerId());
                        List<Long> userTypeIdList = new ArrayList<>();
                        for (UserType userType: userTypeList) {
                            userTypeIdList.add(userType.getId());
                        }
                        wechatUserQuery.setUserTypeList(userTypeIdList);
                        Page<WechatUser> page = new Page<>();
                        page.setSize(5);
                        page.setCurrent(1);
                        List<WechatUser> wechatUserList =  wechatUserMapper.findByList(page, wechatUserQuery);
                        //表示有用户在使用该组内的会员类型
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已经有用户使用了该配置方案的会员类型组内的会员类型");
                        }
                    }
                }
            }
        }

        //用户会员组
        configPlan.setUserTypeGroupId(configPlanProfitUpdateDto.getUserTypeGroupId());

        //淘宝分佣规则ID
        configPlan.setTbCommissionPlanId(configPlanProfitUpdateDto.getTbCommissionPlanId());

        //京东分佣方案ID
        configPlan.setJdCommissionPlanId(configPlanProfitUpdateDto.getJdCommissionPlanId());

        //拼多多分佣方案
        configPlan.setPddCommissionPlanId(configPlanProfitUpdateDto.getPddCommissionPlanId());

        //唯品会分佣方案
        configPlan.setVphCommissionPlanId(configPlanProfitUpdateDto.getVphCommissionPlanId());

        //本地生活分佣方案
        configPlan.setLocalLiveCommissionPlanId(configPlanProfitUpdateDto.getLocalLiveCommissionPlanId());

        //抖音分佣方案
        configPlan.setDyCommissionPlanId(configPlanProfitUpdateDto.getDyCommissionPlanId());

        //抖音分佣方案
        configPlan.setDyCommissionPlanId(configPlanProfitUpdateDto.getDyCommissionPlanId());

        //修改配置方案
        configPlanMapper.update(configPlan);

    }

    /**
     * 查询淘宝联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findTbTokenSelectList(Long merId){
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(merId);
        //tbTokenQuery.setIsPh(0); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(0); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);

        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(tbToken.getId());
                SelectIdVo.setValue(String.valueOf(tbToken.getUserName()));
                tbTokenVoList.add(SelectIdVo);
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询饿了么联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findElmTokenSelectList(Long merId){
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(merId);
        //tbTokenQuery.setIsPh(0); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(1); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);

        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(tbToken.getId());
                SelectIdVo.setValue(String.valueOf(tbToken.getUserName()));
                tbTokenVoList.add(SelectIdVo);
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询炮灰淘宝联盟下拉列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPhTbTokenSelectList(Long merId){
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(merId);
        //tbTokenQuery.setIsPh(1); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(0); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);
        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(tbToken.getId());
                SelectIdVo.setValue(String.valueOf(tbToken.getUserName()));
                tbTokenVoList.add(SelectIdVo);
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询唯品会联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findVphTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> vphTokenVoList = new ArrayList<SelectIdVo>();

        VphTokenQuery vphTokenQuery = new VphTokenQuery();
        vphTokenQuery.setMerId(merId);
        //vphTokenQuery.setIsPh(0);
        List<VphToken> vphTokenList = vphTokenMapper.findByList(vphTokenQuery);
        if(vphTokenList != null){
            for (VphToken vphToken : vphTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(vphToken.getId());
                SelectIdVo.setValue(String.valueOf(vphToken.getOpenId()));
                vphTokenVoList.add(SelectIdVo);
            }
        }
        return vphTokenVoList;
    }

    /**
     * 查询炮灰唯品会联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPhVphTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> vphPhTokenVoList = new ArrayList<SelectIdVo>();

        VphTokenQuery vphTokenQuery = new VphTokenQuery();
        vphTokenQuery.setMerId(merId);
        //vphTokenQuery.setIsPh(1);
        List<VphToken> vphTokenList = vphTokenMapper.findByList(vphTokenQuery);
        if(vphTokenList != null){
            for (VphToken vphToken : vphTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(vphToken.getId());
                SelectIdVo.setValue(String.valueOf(vphToken.getOpenId()));
                vphPhTokenVoList.add(SelectIdVo);
            }
        }
        return vphPhTokenVoList;
    }

    /**
     * 查询京东联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findJdTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> jdTokenVoList = new ArrayList<SelectIdVo>();

        JdTokenQuery jdTokenQuery = new JdTokenQuery();
        jdTokenQuery.setMerId(merId);
        List<JdToken> jdTokenList = jdTokenMapper.findByList(jdTokenQuery);
        if(jdTokenList != null){
            for (JdToken jdToken : jdTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(jdToken.getId());
                SelectIdVo.setValue(String.valueOf(jdToken.getUnionId()));
                jdTokenVoList.add(SelectIdVo);
            }
        }

        return jdTokenVoList;
    }

    /**
     * 查询拼多多联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPddTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> pddTokenVoList = new ArrayList<SelectIdVo>();

        PddTokenQuery pddTokenQuery = new PddTokenQuery();
        pddTokenQuery.setMerId(merId);
        List<PddToken> pddTokenList = pddTokenMapper.findByList(pddTokenQuery);
        if(pddTokenList != null){
            for (PddToken pddToken : pddTokenList) {
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(pddToken.getId());
                selectIdVo.setValue(String.valueOf(pddToken.getUserName()));
                pddTokenVoList.add(selectIdVo);
            }
        }
        return pddTokenVoList;
    }

    /**
     * 查询抖音联盟下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findDyTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> pddTokenVoList = new ArrayList<SelectIdVo>();

        DyTokenQuery dyTokenQuery = new DyTokenQuery();
        dyTokenQuery.setMerId(merId);
        List<DyToken> dyTokenList = dyTokenMapper.findByList(dyTokenQuery);
        if(dyTokenList != null){
            for (DyToken dyToken : dyTokenList) {
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(dyToken.getId());
                selectIdVo.setValue(String.valueOf(dyToken.getName()));
                pddTokenVoList.add(selectIdVo);
            }
        }
        return pddTokenVoList;
    }


    /**
     * 查询推老板共享账号下拉选择列表
     * @param tlbTokenQuery
     * @return null
     */
    public List<SelectIdVo> findTlbTokenSelectList(TlbTokenQuery tlbTokenQuery){
        //新建返回页面对象
        List<SelectIdVo> tlbTokenVoList = new ArrayList<SelectIdVo>();
        //循环推老板联盟账户
        List<TlbToken> tlbTokenList = tlbTokenMapper.findByList(tlbTokenQuery);
        if(tlbTokenList != null){
            for (TlbToken tlbToken : tlbTokenList){
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(tlbToken.getId());
                selectIdVo.setValue(tlbToken.getAppId());
                tlbTokenVoList.add(selectIdVo);
            }
        }
        return tlbTokenVoList;
    }



    /**
     * 查询推广裂变的奖励方案下拉选择列表
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findRegRewardRuleSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> regRewardRuleVoList = new ArrayList<SelectIdVo>();
        RegRewardRuleQuery regRewardRuleQuery = new RegRewardRuleQuery();
        regRewardRuleQuery.setMerId(merId);
        List<RegRewardRule> regRewardRuleList =  regRewardRuleMapper.findByList(regRewardRuleQuery);
        if(regRewardRuleList != null && regRewardRuleList.size() > 0){
            for (RegRewardRule regRewardRule : regRewardRuleList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(regRewardRule.getId());
                SelectIdVo.setValue(regRewardRule.getName());
                regRewardRuleVoList.add(SelectIdVo);
            }
        }
        return regRewardRuleVoList;
    }

    /**
     * 查询域名下拉选择列表
     * @param merId
     * @return null
     */
    public List<SysDomainInfoVo> findSysDomainSelectList(Long merId){
        //新建返回页面对象
        List<SysDomainInfoVo> sysDomainInfoVoList = new ArrayList<>();
        SysDomainQuery sysDomainQuery = new SysDomainQuery();
        sysDomainQuery.setMerId(merId);
        sysDomainQuery.setStatus(1);
        List<SysDomain> sysDomainList =  sysDomainMapper.findByList(sysDomainQuery);
        if(sysDomainList != null && sysDomainList.size() > 0){
            for (SysDomain sysDomain : sysDomainList) {
                SysDomainInfoVo  sysDomainInfoVo = new SysDomainInfoVo();
                BeanUtils.copyProperties(sysDomain, sysDomainInfoVo);
                sysDomainInfoVoList.add(sysDomainInfoVo);
            }
        }
        return sysDomainInfoVoList;
    }

    /**
     * 查询分佣规则下拉选择列表
     * @param configPlanNormalrewardruleDto
     * @return null
     */
    public List<SelectIdVo> findNormalRewardRuleSelectList(ConfigPlanNormalrewardruleDto configPlanNormalrewardruleDto){
        //新建返回页面对象
        List<SelectIdVo> normalRewardRuleVoList = new ArrayList<SelectIdVo>();
        NormalRewardRuleQuery normalRewardRuleQuery = new NormalRewardRuleQuery();
        normalRewardRuleQuery.setMerId(configPlanNormalrewardruleDto.getMerId());
        normalRewardRuleQuery.setUserTypeGroupId(configPlanNormalrewardruleDto.getUserTypeGroupId());
        List<NormalRewardRule> normalRewardRuleList = normalRewardRuleMapper.findByList(normalRewardRuleQuery);
        if(normalRewardRuleList != null){
            for (NormalRewardRule normalRewardRule : normalRewardRuleList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(normalRewardRule.getId());
                SelectIdVo.setValue(normalRewardRule.getName());
                normalRewardRuleVoList.add(SelectIdVo);
            }
        }
        return normalRewardRuleVoList;
    }


}
